<template>
	<div v-if="location">
		经度：{{ location.lng }}，纬度：{{ location.lat }}，精度：{{ location.accuracy }}米
	</div>
	<div id="map-container" style="width:100%; height:500px"></div>


</template>

<script setup>
import { ref, onMounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
const location = ref(null);
// eslint-disable-next-line vue/no-export-in-script-setup
const emit = defineEmits(['success']);
onMounted(async () => {
	// 配置安全密钥
	window._AMapSecurityConfig = {
		securityJsCode: '2b06d933467ca1ee8950bbe7aacfee84' // 替换为你的安全密钥
	};

	try {
		const AMap = await AMapLoader.load({
			key: '36aa605b5ec2faae32b4e82b22c3c573', // 替换为你的高德Key
			version: '2.0',
			plugins: ['AMap.Geolocation']
		});

		// 初始化地图
		const map = new AMap.Map('map-container', {
			zoom: 15,
			resizeEnable: true
		});

		// 创建定位控件
		const geolocation = new AMap.Geolocation({
			enableHighAccuracy: true,  // 高精度定位
			timeout: 10000,           // 超时时间10秒
			buttonPosition: 'RB'      // 定位按钮在右下角
		});

		map.addControl(geolocation);

		// 获取定位结果
		geolocation.getCurrentPosition((status, result) => {
			if (status === 'complete') {
				const { position, accuracy } = result;

				location.value = {
					lng: position.lng.toFixed(6),
					lat: position.lat.toFixed(6),
					accuracy: Math.round(accuracy)
				};
				map.setCenter(position); // 地图中心点定位到当前位置
				// 触发自定义事件，传递定位数据
				emit('success', {
					longitude: position.lng,
					latitude: position.lat
				});

			} else {
				console.error('定位失败:', result);
			}
		});
	} catch (error) {
		console.error('地图加载失败:', error);
	}
});

</script>

